#!/bin/bash

# compiles all the .java files together
# if compilation goes without any errors,
# it builds the .jar file and executes it
# This has made testing JAR's so much easier!

JAR="bump3.jar"
DIR="./bump3/"

DELETETMP=false

echo -e "\033[37m[+] BuMP3 jar packer and executer"
echo -e "\033[37m[+] \033[0mgetting latest revision..."

rm ${DIR}engines/*.class
rm ${DIR}*.class

rm -rf /tmp/rev.html
# wget -q -O /tmp/rev.html "http://code.google.com/p/bump3/source/list"
curl -s -o /tmp/rev.html "http://code.google.com/p/bump3/source/list"

if [[ ! -f /tmp/rev.html ]]; then
  echo -e -n "\033[31m[!] page could not be downloaded! \033[0mcontinue? (y/n): "
  read X
  if [[ $x -eq 'n' ]]; then
    exit 0
  fi
  DELETETMP=true
else
  OLDLINE=$(sed -n '49p' ${DIR}Main.java)
  
  NEWLINE=$(cat /tmp/rev.html | grep -e "detail?r=" | sed -n '1p')
  NEWLINE=${NEWLINE#*detail?r=}
  NEWLINE=${NEWLINE%%\">*}      # "}
  NEWLINE=$((NEWLINE+1))
  NEWLINE="    public static int     REVISION     = ${NEWLINE};"
  if [[ $OLDLINE == $NEWLINE ]]; then
    echo -e "\033[37m[+] \033[0mREVISION in Main.java is already updated"
  else
    echo -e "\033[37m[+] \033[0mline 49 in ${DIR}Main.java is currently:"
    echo -e ""
    echo -e "\033[31m${OLDLINE}"
    echo -e ""
    echo -e "\033[37m[+] \033[0mline 49 will be replaced with:"
    echo -e "\033[32m${NEWLINE}"
    echo -e ""
    echo -e "\033[37m[+] \033[33mdo you want to replace the line, continue compiling, or abort?"
    echo -e "    \033[32m[y]es \033[33m[n]o \033[31m[a]bort"
    read X
    
    if [[ $X == 'y' ]]; then
      # cat ${DIR}Main.java | sed -n '49p'
      sed -i "s/${OLDLINE}/${NEWLINE}/" bump3/Main.java
      #cat ${DIR}MainTest.java | sed -n '49p'
    elif [[ $X == 'a' ]]; then
      exit 0
    fi
    
    if [[ $DELETETMP == true ]]; then
      rm -rf /tmp/rev.html
    fi
  fi
fi


echo -e "\033[37m[+] compiling..."

javac ${DIR}Main.java

if [[ $? -eq 0  ]]
then
    echo -e "\033[37m[+] \033[32mcompiled successfully"
	echo -e "\033[37m[+] building jar file..." # 04B.TTF 
    #jar cvfm ${JAR} theManifest *.class uni0553.TTF COPYING splash.png icon.png bump3.png TOS.txt CHANGES >> /dev/null
    jar cvfm ${JAR} theManifest ${DIR}*.class ${DIR}/engines/*.class ${DIR}uni0553.TTF ${DIR}COPYING ${DIR}splash.png ${DIR}icon.png ${DIR}bump3.png ${DIR}TOS.txt ${DIR}CHANGES > /dev/null
	echo -e "\033[37m[+] executing..."
	echo -e ""
    java -jar ${JAR} $@
else
    echo -e "\033[31m[!] errors occurred while compiling"
fi
